package com.delos.rbac.service.impl;

import com.delos.rbac.error.ExceptionEnum;
import com.delos.rbac.error.ServiceException;
import com.delos.rbac.service.ILoginService;
import com.delos.rbac.service.IUserService;
import com.delos.rbac.util.JwtUtils;
import com.delos.rbac.vo.UserVO;
import com.mysql.cj.protocol.a.authentication.Sha256PasswordPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;

/**
 * @author zouyaowen
 * @date 2020-06-28
 */
@Service
public class LoginServiceImpl implements ILoginService {

    private static final String USER_ID = "userId";
    private static final String USER_NAME = "userName";
    private static final String USER_ROLE_LIST = "userRoleList";

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private IUserService userService;

    @Override
    public String browserLogin(@NotBlank(message = "用户名不能为空") String userName, @NotBlank(message = "密码不能为空") String password) {
        UserVO user = userService.findUser(userName);
        if (!BCrypt.checkpw(password, user.getPassword())) {
            throw new ServiceException(ExceptionEnum.DATA_ERROR, "密码不正确");
        }
        UserVO userDetail = userService.getUserRole(user.getId());
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.put(USER_ID, userDetail.getId().toString());
        userMap.put(USER_NAME, userDetail.getUserName());
        userMap.put(USER_ROLE_LIST, userDetail.getRoleList());
        return jwtUtils.generateToken(userMap);
    }
}
